package com.yssoft.service.core;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yssoft.datasource.DataSource;
import com.yssoft.entity.core.TAccounts;
import com.yssoft.entity.core.TPersonnel;
import com.yssoft.mapper.core.TAccountsMapper;
import com.yssoft.mapper.core.TPersonnelMapper;
import com.yssoft.mapper.core.TRolesMapper;
import com.yssoft.shiro.MyRealm;
import com.yssoft.utils.LayuiUtil;
import com.yssoft.utils.UserHelper;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 账号信息
 */
@Service
public class AccountsService {
    
    /**
     * mapper
     */
    @Resource
    private TAccountsMapper accountsMapper;
    @Resource
    private TPersonnelMapper personnelMapper;
    @Resource
    private TRolesMapper rolesMapper;
    
    /**
     * 新增账号
     * @param accounts
     * @param roles
     */
    @Transactional(rollbackFor = Exception.class)
    public int addAcc(TAccounts accounts, String[] roles){
        String salt= System.currentTimeMillis()+Math.ceil(Math.random())+"";
        accounts.setSalt(salt);//随机加密盐
        String password = new SimpleHash("MD5", accounts.getPassword(), accounts.getSalt(), 2).toString();
        accounts.setPassword(password);
        accounts.setCreateTime(new Date());
        MyRealm.ShiroUser shiroUser=UserHelper.getCurrentUser();
        accounts.setDeleteFlag("0");
        accounts.setCreatorId(shiroUser.getPersonId());
        accounts.setCreatorName(shiroUser.getName());
        accounts.settEId(UserHelper.getCurrentCompanyId());
        accountsMapper.insert(accounts);
        Map<String,Object> param=new HashMap<>();
        param.put("list",Arrays.asList(roles));
        param.put("accountId",accounts.getId());
        return accountsMapper.insertAccountAndRole(param);//往账号和角色的中间表中添加数据
    }
    
    /*
     * 根据用户登陆账号查询实体
     * @param loginName登陆账号
     */
    public TAccounts queryAccByLoginName(String loginName){
        return accountsMapper.selectByLoginName(loginName);
    }
    
    
    /**
     * 分页查询当前企业的账号信息
     * @param page 第几页
     * @param limit 每页数量
     * @param personName 人员名称
     * @param loginName 登陆名
     * @return
     */
    public JSONObject queryAccountPage(int page, int limit, String personName, String loginName) {
        Integer companyId = UserHelper.getCurrentCompanyId();//当前登陆人企业
        PageHelper.startPage(page,limit);
        Map<String,Object> params=new HashMap<>();
        params.put("companyId" , companyId);
        params.put("personName",personName);
        params.put("loginName",loginName);
        List<Map<String,Object>> pagelist = accountsMapper.queryAccountPage(params);
        int pageCount = accountsMapper.queryAccountCount(params);
        return LayuiUtil.getJSONObjectByMap(pagelist,pageCount,"","");
    }
    
    /**
     * 多条删除账号信息
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int delAccountByIds(String ids) {
        int i=0;
        String [] idArray=ids.split(",");
        for (String id : idArray) {
            TAccounts accounts=new TAccounts();
            accounts.setDeleteFlag("1");
            accounts.setId(Integer.parseInt(id));
            i+=accountsMapper.updateByPrimaryKeySelective(accounts);
        }
        return i;
    }
    
    /**
     * 删除单挑账号信息
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int delAccountById(String id) {
        TAccounts accounts=new TAccounts();
        accounts.setDeleteFlag("1");
        accounts.setId(Integer.parseInt(id));
        return  accountsMapper.updateByPrimaryKeySelective(accounts);
    }
    
    /**
     * 根据账号id查询账号信息
     * @param id
     * @return
     */
    public TAccounts queryAccById(Integer id) {
        return accountsMapper.selectByPrimaryKey(id);
    }
    
    /**
     * 根据账号id修改账号信息
     * @param accounts
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateAccountById(TAccounts accounts) {
        return accountsMapper.updateByPrimaryKeySelective(accounts);
    }
    
    /**
     * 根据人员查询出这个人员的账号
      * @param id
     * @return
     */
    public TAccounts queryAccountByPersonId(Integer id) {
        return accountsMapper.selectByPersonId(id);
    }
    
    /**
     * 查询当前企业中号的人员
     * @return
     * @param page
     * @param limit
     */
    public JSONObject queryCurrentEntPersonPage(int page, int limit) {
        PageHelper.startPage(page,limit);
        List<TPersonnel> personList = personnelMapper.selectMyEntPerson(UserHelper.getCurrentCompanyId());
        int  count = personnelMapper.selectMyEntPersonCount(UserHelper.getCurrentCompanyId());
        try {
           return  LayuiUtil.getJSONObjectByObject(personList,count,"","");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 解除绑定
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateRelievePeron(String id) {
 
        return  accountsMapper.updatePersonNullByPrimaryKey(id);
    }
    
    /**
     * 查询账号是否存在
     * @param loginName
     * @return
     */
    public Integer queryAccountRepeat(String loginName) {
         TAccounts account= accountsMapper.selectByLoginName(loginName);
        if(account!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    /**
     * 清空账号密码
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer accountEmpty(String id) {
        TAccounts accounts=new TAccounts();
        String salt= System.currentTimeMillis()+Math.ceil(Math.random())+"";
        accounts.setSalt(salt);//随机加密盐
        String password = new SimpleHash("MD5", "123456", accounts.getSalt(), 2).toString();
        accounts.setId(Integer.parseInt(id));
        accounts.setPassword(password);
        return  accountsMapper.updateByPrimaryKeySelective(accounts);
    }
    
    /**
     * 修改账号信息和对应的角色
     * @param accounts
     * @param roles
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateAccountByIdAndRole(TAccounts accounts, String[] roles) {
        accountsMapper.updateByPrimaryKeySelective(accounts);
        accountsMapper.deleteAccountAndRole(accounts.getId());
        Map<String,Object> param=new HashMap<>();
        param.put("list",Arrays.asList(roles));
        param.put("accountId",accounts.getId());
        return accountsMapper.insertAccountAndRole(param);
    }
	/**
	 * 查询账号所有的角色
	 * @param id
	 * @return
	 */
	public List<String> queryRolesByAccId(Integer id) {
		return accountsMapper.queryRolesByAccId(id);
	}
	
	/**
	 *根据帐号id获取权限 
	 */
	public Set<String> queryPermissionForList(Integer id) {
		
		return this.accountsMapper.queryPermissionForList(id);
	}
}
